package com.key.service.impl;

import com.github.pagehelper.PageHelper;
import com.key.common.dto.*;
import com.key.common.vo.AssetsVO;
import com.key.common.vo.StocktakingAssetsVO;
import com.key.common.vo.StocktakingFormDetailsVO;
import com.key.entity.Assets;
import com.key.entity.RepairForm;
import com.key.entity.StocktakingForm;
import com.key.entity.StocktakingResult;
import com.key.mapper.AssetsMapper;
import com.key.mapper.EmployeeMapper;
import com.key.mapper.StocktakingFormMapper;
import com.key.service.AssetCodeService;
import com.key.service.StocktakingFormService;
import com.key.utils.EntityConversion;
import com.key.utils.ExcelExportHelper;
import com.key.utils.OddNumbersUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wei
 */
@Service
public class StocktakingFormServiceImpl implements StocktakingFormService {

    @Autowired
    private AssetCodeService assetCodeService;

    @Autowired
    private StocktakingFormMapper stocktakingFormMapper;

    @Autowired
    private AssetsMapper assetsMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EntityConversion entityConversion;

    @Override
    @Transactional
    public boolean addStocktakingForm(StocktakingFormDTO stocktakingFormDTO) {

        AssetsFindDTO assetsFindDTO = EntityConversion.StocktakingFormDTOToAssetsFindDTO(stocktakingFormDTO);

        List<AssetsVO> assetsVOList = assetsMapper.selectAssetsList(assetsFindDTO);

        String sfNo = OddNumbersUtils.creatON("PD");

        int i = 0;
        int j = 0;
        int k = 0;

        if(assetsVOList.size() > 0){
            //往stocktaking_form表里添加数据
            Date date = new Date();
            Timestamp now = new Timestamp(date.getTime());
            StocktakingForm stocktakingForm = EntityConversion.StocktakingFormDTOToStocktakingForm(stocktakingFormDTO, now);
            stocktakingForm.setSfNo(sfNo);
            stocktakingForm.setSfState(1);

            i = stocktakingFormMapper.insertStocktakingForm(stocktakingForm);

            //往stocktaking_emp表里添加数据
            List<String> empsName = stocktakingFormDTO.getAssignEmpsName();
            Integer emp;
            for(String empName : empsName){
                emp = employeeMapper.selectEmpIdByEmpName(empName);
                j = stocktakingFormMapper.insertStocktakingEmp(emp, sfNo);
            }

            //往stocktaking_result表里添加数据
            //根据新建盘点单时填入的盘点范围查询资产
            for(AssetsVO assetsVO : assetsVOList){
                StocktakingResult stocktakingResult = EntityConversion.AssetsVOToStocktakingResult(assetsVO, now);
                stocktakingResult.setSfNo(sfNo);
                stocktakingResult.setSrState(1);
                k = stocktakingFormMapper.insertStocktakingResult(stocktakingResult);
            }
        }

        return i > 0 && j > 0 && k > 0;
    }

    @Override
    @Transactional
    public boolean removeStocktakingForm(String sfNo) {

        int i = stocktakingFormMapper.deleteStocktakingForm(sfNo);
        int j = 0, k = 0;
        if(i != 0){
            j = stocktakingFormMapper.deleteStocktakingResult(sfNo);
            k = stocktakingFormMapper.deleteStocktakingEmp(sfNo);
        }

        return i > 0 && j > 0 && k > 0;
    }

    @Override
    public Map<String, Object> findStocktakingForm(StocktakingFormFindDTO stocktakingFormFindDTO) {
        Map<String, Object> map = new HashMap<>();

        List<StocktakingForm> stocktakingFormList;
        if(stocktakingFormFindDTO.getCurrentPage() != null && stocktakingFormFindDTO.getPageSize() != null){
            //分页
            PageHelper.startPage(stocktakingFormFindDTO.getCurrentPage(), stocktakingFormFindDTO.getPageSize());
            stocktakingFormList = stocktakingFormMapper.selectStocktakingForm(stocktakingFormFindDTO);
        }else{
            //不分页
            stocktakingFormList = stocktakingFormMapper.selectStocktakingForm(stocktakingFormFindDTO);
        }

        Integer count = stocktakingFormMapper.getStocktakingFormCount(stocktakingFormFindDTO);

        map.put("stocktakingFormList", stocktakingFormList);
        map.put("count", count);

        return map;
    }

    @Override
    public StocktakingFormDetailsVO findStocktakingFormDetailsVOBySfNo(String sfNo) {

        List<String> EmployeeNameList = stocktakingFormMapper.selectEmployeeNameBySfNo(sfNo);
        StocktakingForm stocktakingForm = stocktakingFormMapper.selectStocktakingFormBySfNo(sfNo);

        StocktakingFormDetailsVO stocktakingFormDetailsVO = EntityConversion.stocktakingFormToStocktakingFormDetailsVO(EmployeeNameList, stocktakingForm);

        return stocktakingFormDetailsVO;
    }

    @Override
    public List<String> findEmployeeBySfNo(String sfNo) {
        return stocktakingFormMapper.selectEmployeeNameBySfNo(sfNo);
    }

    @Override
    public boolean editAssignedUsers(String sfNo, List<String> assignEmpsName) {

        //首先删除全部的分配用户
        int i = stocktakingFormMapper.deleteStocktakingEmp(sfNo);

        //再根据前端返回的用户添加数据
        int j = 0;
        Integer emp;
        for(String assignEmpName : assignEmpsName){
            emp = employeeMapper.selectEmpIdByEmpName(assignEmpName);
            j = stocktakingFormMapper.insertStocktakingEmp(emp, sfNo);
        }

        return i > 0 && j > 0;
    }

    @Override
    public List<Map<String, Object>> findIncompleteEmployees(String sfNo) {
        return stocktakingFormMapper.selectIncompleteEmployeesBySfNo(sfNo);
    }

    @Override
    public Map<String, Object> findStocktakingAssetsBySfNo(Integer currentPage, Integer pageSize, String sfNo) {

        Map<String, Object> map = new HashMap<>();

        List<StocktakingAssetsVO> stocktakingAssetsVOList;

        Subject subject = SecurityUtils.getSubject();
        String s = String.valueOf(subject.getPrincipal());

        Integer employeeId = employeeMapper.selectEmpIdByEmpName(s);

        if(currentPage != null && pageSize != null || currentPage != 0 && pageSize != 0){
            //分页
            PageHelper.startPage(currentPage, pageSize);
            stocktakingAssetsVOList = stocktakingFormMapper.selectStocktakingAssetsBySfNo(sfNo, employeeId);
        }else{
            //不分页
            stocktakingAssetsVOList = stocktakingFormMapper.selectStocktakingAssetsBySfNo(sfNo, employeeId);
        }

        Integer count = stocktakingFormMapper.getStocktakingAssetsCountBySfNo(sfNo);

        map.put("stocktakingAssetsVOList", stocktakingAssetsVOList);
        map.put("count", count);

        return map;
    }

    @Override
    public boolean removeStocktakingSurplus(StocktakingSurplusDTO stocktakingSurplusDTO) {

        String sfNo = stocktakingSurplusDTO.getSfNo();
        List<Long> assetsIds = stocktakingSurplusDTO.getAssetsIds();

        int i = assetsMapper.deleteAssets(assetsIds);
        int j = 0;

        if(i != 0){
            j = stocktakingFormMapper.deleteStocktakingSurplus(sfNo, assetsIds);
        }

        return i > 0 && j > 0;
    }

    @Override
    public boolean editStocktakingAsset(StocktakingSurplusDTO stocktakingSurplusDTO) {

        Date date = new Date();
        Timestamp now = new Timestamp(date.getTime());

        stocktakingSurplusDTO.setSrStocktakingTime(now);

        int i = stocktakingFormMapper.updateStocktakingResult(stocktakingSurplusDTO);

        return i > 0;
    }

    @Override
    public boolean submitStocktaking(String sfNo) {

        boolean result = false;

        int i = stocktakingFormMapper.getNotStocktakingCount(sfNo);
        int j = 0;

        //当未盘点数为0时，说明已经盘点完
        if(i != 0){
            result = true;
            j = stocktakingFormMapper.submitStocktakingForm(sfNo);
        }
        return result && j > 0;
    }

    @Override
    public boolean addStocktakingSurplus(StocktakingAssetDTO stocktakingAssetDTO) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String time = new String(format.format(new Date())+" 00:00:00");
        Timestamp now = Timestamp.valueOf(time);

        Assets assets = entityConversion.StocktakingAssetDTOToAssets(stocktakingAssetDTO,now);

        assets.setAssetsCode(assetCodeService.getCode());

        StocktakingResult stocktakingResult = EntityConversion.StocktakingAssetDTOToStocktakingResult(stocktakingAssetDTO);

        int i = assetsMapper.addAssets(assets);
        Long assetsId = assetsMapper.selectAssetsId(assets);
        int j = 0;

        if(i != 0){
            stocktakingResult.setSrResult("盘盈");
            stocktakingResult.setSrState(2);
            stocktakingResult.setAssetsId(assetsId);
            stocktakingResult.setSrStocktakingTime(now);
            stocktakingResult.setSrCreateTime(now);
            j = stocktakingFormMapper.insertStocktakingResult(stocktakingResult);
        }

        return i > 0 && j > 0;
    }


    @Override
    public HSSFWorkbook getWorkBook(String sfNo) {
        String[] header = {"资产id", "状态(1:未盘点，2:已盘点)", "资产照片", "标签", "资产类别", "设备序列号","资产编码","规格型号","计量单位",
                "原来的区域名称","原来的资产存放点","原来的使用公司","原来的使用部门","所属公司","原来的使用人","修改后的区域","修改后的存放地点",
                "修改后的使用公司","修改后的使用人","盘点人","盘点时间","盘点备注"};
        String[] properties = {"assetsId", "srState", "assetsPhoto", "label", "assetTypeName", "assetsSerialNumber", "assetsCode",
                "modelName", "unit", "originalAssetsRegion","originalAssetsStorageLocation","originalCompanyName","originalDepartmentName",
                "assetsAdmin","originalEmployeeName","editedAssetsRegion","editedAssetsStorageLocation","editedCompanyName",
                "editedEmployeeName","srStocktakingMan","srStocktakingTime","srRemark"};
        Integer employeeId = null;
        List<StocktakingAssetsVO> stocktakingAssetsVOList = stocktakingFormMapper.selectStocktakingAssetsBySfNo(sfNo,employeeId);
        List list = new ArrayList();
        for (StocktakingAssetsVO stocktakingAssetsVO : stocktakingAssetsVOList) {
            list.add(stocktakingAssetsVO);
        }
        ExcelExportHelper excelHelper = new ExcelExportHelper();
        HSSFWorkbook workbook = excelHelper.exportExcel(header, properties, list, "盘点资产列表");
        return workbook;
    }

    @Override
    public HSSFWorkbook getWorkBook() {
        String[] header = {"盘点主键ID", "盘点单号", "盘点单名称", "备注", "创建人", "状态(1:未完成，2:已完成)","创建时间","是否全员盘点(1:是，2:否)","盘点时是否必须牌照(1:是，2:否)",
                "是否允许手动选择资产盘点(1:是，2:否)","盘点是否允许牌照上(1:是，2:否)","是否包含已经调出未确认资产(1:是，2:否)"};
        String[] properties = {"sfId", "sfNo", "sfName", "sfRemark", "sfCreater", "sfState", "sfCreateTime",
                "sfIsAll", "sfIsPlate", "sfIsManual","sfIsUpload","sfIsContainCallout"};
        List<StocktakingForm> stocktakingFormList = stocktakingFormMapper.selectStocktakingFormList();
        List list = new ArrayList();
        for (StocktakingForm stocktakingForm : stocktakingFormList) {
            list.add(stocktakingForm);
        }
        ExcelExportHelper excelHelper = new ExcelExportHelper();
        HSSFWorkbook workbook = excelHelper.exportExcel(header, properties, list, "盘点清单列表");
        return workbook;
    }
}
